package org.dromara.one.excel;

import cn.hutool.core.lang.UUID;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFConditionalFormattingRule;
import org.apache.poi.xssf.usermodel.XSSFDataBarFormatting;
import org.apache.poi.xssf.usermodel.XSSFSheetConditionalFormatting;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelProgressBars {
    public static void main(String[] args) {

        String downloadPath = "D://"+ UUID.randomUUID().toString() + "_" + "MTD总览.xlsx";
        ExcelWriter excelWriter = EasyExcel.write(downloadPath, null).excelType(ExcelTypeEnum.XLSX).build();
        Workbook targetWorkbook =excelWriter.writeContext().writeWorkbookHolder().getWorkbook();
        Sheet sheet = targetWorkbook.createSheet("Progress Bars"); // 创建工作表
        getExcelProgressBars(sheet);
        // 写出到文件
        String downloadPath1 = "D://"+ UUID.randomUUID().toString() + "_" + "MTD总览.xlsx";


        try (FileOutputStream outputStream = new FileOutputStream(downloadPath1)) {
            targetWorkbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭工作簿资源
        try {
            targetWorkbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }





    public static void getExcelProgressBars(Sheet sheet){

        // 假设我们的进度数据在B列，从第二行开始
        for (int i = 1; i <= 10; i++) {
            Row row = sheet.createRow(i);
            Cell cell = row.createCell(1);
            double progress = i * 0.1; // 百分比值，比如0.1表示10%
            cell.setCellValue(progress * 100); // 单元格设置百分比值(乘以100，Excel中通常是基于整数)
        }

        // 使用Apache POI的条件格式创建进度条
        XSSFSheetConditionalFormatting conditionalFormatting = (XSSFSheetConditionalFormatting) sheet.getSheetConditionalFormatting();

        XSSFConditionalFormattingRule rule = conditionalFormatting.createConditionalFormattingRule("");
        XSSFDataBarFormatting dataBarFormatting = rule.createDataBarFormatting(new XSSFColor());
        dataBarFormatting.getMinThreshold().setRangeType(ConditionalFormattingThreshold.RangeType.NUMBER);
        dataBarFormatting.getMinThreshold().setValue(0D);
        dataBarFormatting.getMaxThreshold().setRangeType(ConditionalFormattingThreshold.RangeType.NUMBER);
        dataBarFormatting.getMaxThreshold().setValue(100D);

        // 设置进度条的颜色（可以根据自己的需求修改）
        dataBarFormatting.getColor().setARGBHex("FF0070C0"); // 蓝色

        // 引用B2到B11区域的单元格
        CellRangeAddress[] regions = {CellRangeAddress.valueOf("B2:B11")};

        conditionalFormatting.addConditionalFormatting(regions, rule);

        // 调整列宽以显示进度条
        sheet.setColumnWidth(1, 20 * 256); // 设定列的宽度
    }


}
